<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :before-show="true">
        <span slot="before">共{{ page.total }}条数据</span>
        <template v-slot:after>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">导入</el-button>
          <el-button type="danger" size="small" @click="exportData">导出</el-button>
          <el-button :disabled="!checkPerm('POINT-USER-ADD')" icon="el-icon-plus" type="primary" size="small" @click="addEmployee">新增员工</el-button>
        </template>
      </PageTools>
      <el-card v-loading="loading">
        <el-table :data="arr" border="">
          <el-table-column label="序号" sortable type="index" />
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="头像" align="center" width="120px">
            <template v-slot="{row}">
              <img v-imgerror="require('@/assets/common/bigUserHeader.png')" :src="row.staffPhoto" alt="" style="width: 100px; height: 100px;" @click="showQrcode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" sortable prop="formOfEmployment" :formatter="formOfEmployment" />
          <el-table-column label="部门" sortable prop="departmentName" />
          <el-table-column label="入职时间" sortable>
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable prop="enableState">
            <template slot-scope="{row}">
              <el-switch
                :value="row.enableState === 1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination :total="page.total" :current-page="page.page" :page-size="page.size" layout="prev, pager, next" @current-change="handlePage" />
        </el-row>
      </el-card>
      <Add :show-dialog.sync="showDialog" @updata="getemployees" />
      <el-dialog title="二维码" :visible.sync="showCode">
        <el-row type="flex" justify="center">
          <canvas ref="qrcode" />
        </el-row>
      </el-dialog>
      <AssignRole :id="id" ref="role" :show-assign-role.sync="showAssignRole" @closeRole="showAssignRole = false" />
    </div>
  </div>
</template>

<script>
import { getemployees, delEmployee } from '@/api/employees'
import employeesEnum from '@/api/constant/employees'
import Add from './components/add.vue'
import Enum from '@/api/constant/employees'
import { formatDate } from '@/filters'
import Qrcode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  components: {
    Add,
    AssignRole
  },
  data() {
    return {
      loading: false,
      arr: [],
      page: {
        total: 0,
        page: 1,
        size: 10
      },
      showDialog: false,
      showCode: false,
      showAssignRole: false,
      id: ''
    }
  },
  created() {
    this.getemployees()
  },
  methods: {
    async assignRole(id) {
      this.id = id
      await this.$refs.role.getCurrentRoles()
      await this.$refs.role.getRoles()
      this.showAssignRole = true
    },
    showQrcode(url) {
      if (url) {
        this.showCode = true
        this.$nextTick(() => {
          Qrcode.toCanvas(this.$refs.qrcode, url)
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    handlePage(page) {
      this.page.page = page
      this.getemployees()
    },
    async getemployees() {
      this.loading = true
      const { total, rows } = await getemployees(this.page)
      this.loading = false
      this.page.total = total
      this.arr = rows
    },
    formOfEmployment(row, column, cellValue, index) {
      const obj = employeesEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未定义'
    },
    async delEmployee(id) {
      try {
        await this.$confirm('是否确认删除')
        await delEmployee(id)
        this.$message.success('del success')
        this.getemployees()
      } catch (error) {
        console.log(error)
      }
    },
    addEmployee() {
      this.showDialog = true
    },
    exportData() {
      // alert(1)
      import('@/vendor/Export2Excel').then(async({ export_json_to_excel }) => {
        // console.log(export_json_to_excel)
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }

        const { rows } = await getemployees({ page: 1, size: this.page.total })

        export_json_to_excel({
          header: Object.keys(headers),
          data: formatJson(rows),
          multiHeader: [['姓名', '全部信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2']
        })

        // console.log(rows)
        function formatJson(rows) {
          // console.log(rows)
          return rows.map(obj => {
            return Object.keys(headers).map(key => {
              if (key === '入职日期' || key === '转正日期') {
                return formatDate(obj[headers[key]])
              } else if (key === '聘用形式') {
                const res = Enum.hireType.find(item => item.id === 1)
                // console.log(Enum.hireType, res)
                return res ? res.value : '未定义'
              }
              return obj[headers[key]]
            })
          })
        }
        // console.log(formatJson(rows))
      })
    }
  }
}
</script>

<style>

</style>
